package com.yugao.fintech.draper.rabbitmq.config;

import com.yugao.fintech.draper.rabbitmq.support.RabbitMqInitializer;
import com.yugao.fintech.draper.rabbitmq.support.RabbitMqProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@EnableConfigurationProperties(RabbitMqProperties.class)
@AutoConfiguration
@Slf4j
public class RabbitMQConfig {

	/**
	 * 消息序列化配置
	 */
	@Bean
	public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
		SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
		factory.setConnectionFactory(connectionFactory);
		factory.setMessageConverter(new Jackson2JsonMessageConverter());
		return factory;
	}

	/**
	 * 动态创建队列、交换机初始化器
	 */
	@Bean
	@ConditionalOnMissingBean
	public RabbitMqInitializer rabbitModuleInitializer(AmqpAdmin amqpAdmin,
													   RabbitMqProperties rabbitMqProperties) {
		return new RabbitMqInitializer(amqpAdmin, rabbitMqProperties);
	}

}
